//
//  SQLiteHelper.m
//  CC
//
//  Created by Calvin.wang on 3/24/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//  http://www.cocoachina.com/ios/20141111/10190.html

#import "SQLiteHelper.h"
#ifndef DATABASE_NAME
#define DATABASE_NAME  @"CC.db"
#endif

@interface SQLiteHelper()

@end

@implementation SQLiteHelper

#pragma mark overwrite init method
- (instancetype)init
{
    SQLiteHelper *sqliteHelper;
    if ((sqliteHelper = [super init])) {
        [sqliteHelper openDB:DATABASE_NAME];
    }
    
    return sqliteHelper;
}

-(void) openDB:(NSString *)dbname{
    //get the path of db
    NSString *dictionary=[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@",dictionary);
    NSString *filePath=[dictionary stringByAppendingPathComponent:dbname];
    if (SQLITE_OK==sqlite3_open(filePath.UTF8String, &_database)) {
        NSLog(@"open database success");
    }
    else{
        NSLog(@"open database failed");
    }
}

-(void) executeNonQuery:(NSString *)sql{
    char *error;
    
    if (SQLITE_OK!=sqlite3_exec(_database, sql.UTF8String, NULL, NULL, &error)) {
        NSLog(@"execute query error : %s",error);
    }
}

-(NSArray *) executeQuery:(NSString *)sql{
    NSMutableArray *rows=[NSMutableArray array];
    sqlite3_stmt *stmt;
    if(SQLITE_OK==sqlite3_prepare_v2(_database, sql.UTF8String, -1, &stmt, NULL)){
        while (SQLITE_ROW==sqlite3_step(stmt)) {
            int columnCount=sqlite3_column_count(stmt);
            NSMutableDictionary *dic =[NSMutableDictionary dictionary];
            for (int i=0; i<columnCount; i++) {
                const char *name=sqlite3_column_name(stmt, i);
                const unsigned char *value=sqlite3_column_text(stmt, i);
                dic[[NSString stringWithUTF8String:name]]=[NSString stringWithUTF8String:(const char *)value];
            }
            
            [rows addObject:dic];
        }
    }
    sqlite3_finalize(stmt);
    return rows;
}




@end
